#include "Lushanhu.h"
#include "ui_Lushanhu.h"
#include<QtGlobal>
#include<QTime>
#include<QDialog>
#include<QPushButton>
#include<QVBoxLayout>
#include <random>

//后期完善可以增加人物动画
Lushanhu::Lushanhu(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Lushanhu)
    , scene(new QGraphicsScene(this))
    , felyne(nullptr)
    , luBackground(nullptr)
    , luBackground1(nullptr)
    , gameOverDialog(nullptr)
{
    srand(QTime(0,0,0).secsTo(QTime::currentTime()));//拿出来：由于updateGame每秒会被调用约 60 次，而时间间隔较短，多次设置相同的种子会让随机数序列重复
    setupScene();

}

Lushanhu::~Lushanhu()
{
    cleanupTimer();
    cleanupScene();

    if (scene) {
        delete scene;
        scene = nullptr;
    }

    if (ui) {
        delete ui;
        ui = nullptr;
    }
}

void Lushanhu::setupScene()
{
    // 加载地图背景
    ui->setupUi(this);
    // 初始化图形视图
    ui->graphicsView->setScene(scene);
    setWindowTitle("艾露猫：老大我会飞了喵");
    // 窗口大小（物理像素）
    this->setFixedSize(1200, 760); //1800/1.5, 1140/1.5 和缩放抵消
    // graphicsView 大小（逻辑像素，与窗口一致）
    ui->graphicsView->setFixedSize(1200, 760);
    // 设置场景大小（逻辑像素，与背景图一致）
    scene->setSceneRect(0, 0, 1800, 1140);
    // 调整 graphicsView 的变换矩阵，使 1800x1140 的场景适配 1200x760 的视图
    ui->graphicsView->setTransform(QTransform::fromScale(1200.0/1800.0, 760.0/1140.0));
    // 分数显示
    ui->scoreLabel->setGeometry(900, 30, 200, 30);
    ui->scoreLabel->setStyleSheet("QLabel { color: white; font-size: 16px; }");
    // 游戏计时器
    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, &Lushanhu::updateGame);
    gameTimer->start(16); // ~60FPS

    luBackground = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/lushanhu.jpg"));//背景
    luBackground1 = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/lushanhu.jpg"));//背景
    luBackground->setPos(0, 0);  // 明确设置位置
    luBackground1->setPos(1795, 0);
    luBackground->setZValue(-10);
    luBackground1->setZValue(-9);
    scene->addItem(luBackground);
    scene->addItem(luBackground1);

    // 加载角色图片
    felyne = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/you2.png"));
    felyne->setPos(200,380); //
    felyne->setZValue(10);//最上方
    scene->addItem(felyne);
    spawnPipes();
}

//鼠标给我飞起来
void Lushanhu::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        v=-15;
    }
}

//更新位置
void Lushanhu::updateGame() {
    v+=0.6;
    felyne->setPos(felyne->x(), felyne->y() + v);
    luBackground->setPos(luBackground->x() - 1, 0);
    luBackground1->setPos(luBackground1->x() - 1, 0);
    if(luBackground->x() <= -1800) {
        luBackground->setX(luBackground1->x() + 1795);
    }
    if(luBackground1->x() <= -1800) {
        luBackground1->setX(luBackground->x() + 1795);
    }

    // 计时器生成新障碍物
    qreal deltaTime = 1.0 / 60; //固定60FPS
    obstacleTimer += deltaTime;
    if (obstacleTimer >= obstacleInterval) {
        spawnPipes();
        obstacleTimer = 0;
    }

    // 移动障碍物
    for (auto pipe : pipes) {
        pipe->setPos(pipe->x() - 4, pipe->y());
        if (pipe->x() < -200){
            scene->removeItem(pipe);
            delete pipe;
            pipes.removeOne(pipe);
        }
    }

    if(rand()%500==0) spawnPowerUp();
    //移动
    for (auto powerUp : powerUps) {
        powerUp->setPos(powerUp->x() - 4, powerUp->y());
        if (powerUp->x() < -10){
                scene->removeItem(powerUp);
                delete powerUp;
                powerUps.removeOne(powerUp);
        }
    }
    // 检测碰撞
    checkCollisions();

    // 更新分数
    score++;
    ui->scoreLabel->setText(QString("距离: %1米").arg(score/10));
}

void Lushanhu::spawnPipes() {
    //ds写的随机数
    static std::random_device rd;  // 硬件熵源
    static std::mt19937 gen(rd()); // Mersenne Twister引擎
    // 随机参数（范围可调整）
    std::uniform_int_distribution<> centerDist(150, 900); // 中心点Y范围
    std::uniform_int_distribution<> heightDist(190, 280); // 间隙高度范围

    int gapCenter = centerDist(gen);
    int gapHeight = heightDist(gen);


    // 上方障碍物
    QGraphicsPixmapItem *topPipe = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/pipe.png").scaled(200, 1000));
    topPipe->setPos(1700, gapCenter - gapHeight/2 - 1000); // 延伸至屏幕外

    scene->addItem(topPipe);
    pipes.append(topPipe);

    // 下方障碍物
    QGraphicsPixmapItem *bottomPipe = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/pipeb.png").scaled(200, 1000));//这张图是反的
    bottomPipe->setPos(1700, gapCenter + gapHeight/2);
    scene->addItem(bottomPipe);
    pipes.append(bottomPipe);
}

//硬化药
void Lushanhu::spawnPowerUp() {
    QGraphicsPixmapItem* newPowerUp;
    QRect safeArea;
    bool isSafe;
    do {
        isSafe = true;
        safeArea = QRect(1700, 50 + rand() % 400, 30, 30);
        newPowerUp = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/power.jpg"));
        newPowerUp->setPos(safeArea.topLeft());

        // 检查是否与障碍物碰撞
        for (auto pipe : pipes) {
            if (newPowerUp->collidesWithItem(pipe)) {//碰撞函数
                isSafe = false;
                delete newPowerUp;
                break;
            }
        }
    } while (!isSafe);

    powerUps.append(newPowerUp);
    scene->addItem(newPowerUp);
}

// 检查是否与障碍物发生碰撞
bool Lushanhu::isCollidingWithPipes() {
    for (auto pipe : pipes) {
        if (felyne->collidesWithItem(pipe)) {
            return true;
        }
    }
    return false;
}

void Lushanhu::checkCollisions() {
    // 检测障碍物碰撞
    if (!hasPowerUp && isCollidingWithPipes()) {
        gameOver();
        return;
    }

    // 检测边界
    if (felyne->y() < 0 || felyne->y() > 1140) {
        gameOver();
        return;
    }

    // 检测power
    for (auto it = powerUps.begin(); it != powerUps.end(); ) {
        auto powerUp = *it;
        if (felyne->collidesWithItem(powerUp)) {
            scene->removeItem(powerUp);
            delete powerUp;
            it = powerUps.erase(it);
            hasPowerUp = true;
            QTimer::singleShot(10000, this, [this] { hasPowerUp = false; }); // 10秒效果
        } else {
            ++it;
        }
    }
}

//结束界面
void Lushanhu::gameOver() {
    gameTimer->stop();
    //对话框 控制布局
    QDialog dialog(this);
    dialog.setWindowTitle("游戏结束");

    QVBoxLayout layout(&dialog);

    QLabel *text = new QLabel(QString("老大好痛喵！得分: %1米").arg(score/10));
    QPushButton *restart = new QPushButton("再来一局喵");
    QPushButton *exit = new QPushButton("返回地图喵");

    layout.addWidget(text);
    layout.addWidget(restart);
    layout.addWidget(exit);

    connect(restart, &QPushButton::clicked, &dialog, &QDialog::accept);
    connect(exit, &QPushButton::clicked, &dialog, &QDialog::reject);

    if(dialog.exec() == QDialog::Accepted) {
        restartGame();
    } else {
        returnToMap();
    }
}
void Lushanhu::cleanupScene() {
    // 手动删除所有项目
    for (auto pipe : pipes) {
        if (pipe && pipe->scene()) {
            scene->removeItem(pipe);
            delete pipe;
        }
    }
    pipes.clear();

    for (auto power : powerUps) {
        if (power && power->scene()) {
            scene->removeItem(power);
            delete power;
        }
    }
    powerUps.clear();

    // 删除主要图形项
    if (felyne) delete felyne;
    if (luBackground) delete luBackground;
    if (luBackground1) delete luBackground1;
}
void Lushanhu::restartGame() {
    cleanupTimer();
    //清理场景
    cleanupScene();
    // 重置游戏状态
    score = 0;
    v=0;
    hasPowerUp = false;
    obstacleTimer = 0;
    ui->scoreLabel->setText("距离: 0米");


    // 重新初始化//一开始直接调用了scene，setupScene()会重新创建所有UI元素，导致scoreLabel被覆盖
    luBackground = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/lushanhu.jpg"));//背景
    luBackground1 = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/lushanhu.jpg"));//背景
    luBackground->setPos(0, 0);  // 明确设置位置
    luBackground1->setPos(1795, 0);
    luBackground->setZValue(-10);
    luBackground1->setZValue(-9);
    scene->addItem(luBackground);
    scene->addItem(luBackground1);


    // 加载角色图片
    felyne = new QGraphicsPixmapItem(QPixmap(":/image/C:/Users/lenovo/Pictures/iloveimg-resized/you2.png"));
    felyne->setPos(200,380); //
    felyne->setZValue(10);//最上方
    scene->addItem(felyne);

    spawnPipes();
    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, &Lushanhu::updateGame);
    gameTimer->start(16);
}

void Lushanhu::returnToMap() {
    emit backToMap();
    this->hide();
}




